<template>
  <a-card :bordered="false">

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="8">
            <a-form-item label="业务摘要">
              <a-input placeholder="请输入业务摘要" v-model="queryParam.summary"></a-input>
            </a-form-item>
          </a-col>
          <!--<a-col :md="6" :sm="8">-->
            <!--<a-form-item label="已办任务名称">-->
              <!--<a-input placeholder="请输入已办任务名称" v-model="queryParam.taskName"></a-input>-->
            <!--</a-form-item>-->
          <!--</a-col>-->
          <!--<a-col :md="6" :sm="8">
            <a-form-item label="标识key">
              <a-input placeholder="请输入标识key" v-model="queryParam.key"></a-input>
            </a-form-item>
          </a-col>-->
          <!--<a-col :md="6" :sm="8">
            <a-form-item label="name">
              <a-input placeholder="请输入name" v-model="queryParam.name"></a-input>
            </a-form-item>
          </a-col>
        <template v-if="toggleSearchStatus">
        <a-col :md="6" :sm="8">
            <a-form-item label="key">
              <a-input placeholder="请输入key" v-model="queryParam.key"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="category">
              <a-input placeholder="请输入category" v-model="queryParam.category"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="createTime">
              <a-input placeholder="请输入createTime" v-model="queryParam.createTime"></a-input>
            </a-form-item>
          </a-col>
          </template>-->
          <a-col :md="6" :sm="8" >
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <!--<a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>-->
            </span>
          </a-col>

        </a-row>
      </a-form>
    </div>
    <!--<div  v-if="addModel">
    <iframe  :src="modelSrc" style="width: 100%;height: 500px" >
    </iframe>
    </div>-->
    <!-- 操作按钮区域 -->
    <!--<div class="table-operator">-->
      <!--<a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>-->
      <!--&lt;!&ndash;<a-button type="primary" icon="download" @click="handleExportXls('模型管理')">导出</a-button>-->
      <!--<a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">-->
        <!--<a-button type="primary" icon="import">导入</a-button>-->
      <!--</a-upload>&ndash;&gt;-->
      <!--<a-dropdown v-if="selectedRowKeys.length > 0">-->
        <!--<a-menu slot="overlay">-->
          <!--<a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>-->
        <!--</a-menu>-->
        <!--<a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>-->
      <!--</a-dropdown>-->
    <!--</div>-->

    <!-- table区域-begin -->
    <div>
      <div v-if="selectedRowKeys.length > 0" class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :scroll="{ x: 1500 }"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange">

        <span slot="action" slot-scope="text, record">

          <a @click="showDetail(record)">查看</a>

            <a-popconfirm title="确定清理数据吗?" v-if="currentUsername == '管理员'" @confirm="() => cleanProcessData(record)">
              <a-divider type="vertical"/>
              <a>清理数据</a>
            </a-popconfirm>

          <a-popconfirm title="确定撤回到本节点吗?" v-if="record.nextTaskId" @confirm="() => backToThisTask(record)">
              <a-divider type="vertical"/>
              <a>撤回</a>
            </a-popconfirm>

        </span>

        <!-- 字符串超长截取省略号显示-->
        <span slot="summary" slot-scope="text,record"><a-tooltip><template slot="title">{{customRender(record)}}</template>{{customRender(record)}}</a-tooltip></span>


      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <model-modal ref="modalForm" @ok="modalFormOk"></model-modal>
    <history-list ref="modalList" @ok="modalFormOk"></history-list>
    <task-deal-modal :businessKey="businessKey" :taskId="taskId" :pageName="pageUrl"
                     :editUrl="editUrl" :innerpage="innerpage" :internalUrl="internalUrl"
                     ref="taskDealModal" @ok="modalFormOk"></task-deal-modal>
    <!--<model-edit-modal ref="modalEditForm"></model-edit-modal>-->
  </a-card>
</template>

<script>
  import ModelModal from './modules/ModelModal'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { getAction,deleteAction,putAction,postAction} from '@/api/manage'
  import HistoryList from './modules/HistoryList'
  import TaskDealModal from '../../components/page/TaskDealModal'
  import moment from "moment"
  import Vue from 'vue'

  export default {
    name: "TodoList",
    mixins:[JeecgListMixin],
    components: {
      ModelModal,
      TaskDealModal,
      HistoryList
      /*ModelEditModal*/
    },
    data () {
      return {
        description: '我的待办页面',
        // 表头
        columns: [
          // {
          //   title: '#',
          //   dataIndex: '',
          //   key:'rowIndex',
          //   width:60,
          //   align:"center",
          //   customRender:function (t,r,index) {
          //     return parseInt(index)+1;
          //   }
          //  },

		   /*{
            title: '模型ID',
            align:"center",
            dataIndex: 'id'
           },*/
          {
            title: '业务摘要',
            align:"left",
            ellipsis:true,
            dataIndex: 'summary',
            scopedSlots: { customRender: 'summary' },

          },
          // {
          //   title: '流程实例名',
          //   align:"center",
          //   width:180,
          //   dataIndex: 'processDefinitionName'
          // },
		      {
            title: '已办任务名称',
            align:"center",
            width:180,
            dataIndex: 'name'
           },
          {
            title: '审批结果',
            align:"center",
            width:180,
            dataIndex: 'comment'
          },
          {
            title: '耗时',
            align:"center",
            width:180,
            dataIndex: 'duration',
            customRender:function (t,r,index) {
              const duration = r.duration
              var text = ''
              if (duration != null) {
                // text = (duration / 1000 / 60).toFixed(2)
                // return text;
                var text = "";
                var days = Math.floor(duration / (24 * 60 * 60 * 1000));
                if(days != 0){
                  text += days + "天";
                }
                //计算小时数
                var hourLevel = duration % (24 * 60 * 60 * 1000);
                var hours = Math.floor(hourLevel / (60 * 60 * 1000))
                if(hours != 0){
                  text += hours + "小时";
                }
                //计算分钟数
                var minutesLevel = hourLevel % (60 * 60 * 1000);
                var minutes = Math.floor(minutesLevel / (60 * 1000));
                if(minutes != 0){
                  text += minutes + "分";
                }
                //计算秒数
                var seconds = Math.round((minutesLevel % (60 * 1000)) / 1000);
                text += seconds + "秒";

                return text;
              }
              return text;
            }
          },
          // {
          //   title: '工单状态',
          //   align:"center",
          //   width:100,
          //   dataIndex: 'status',
          //   customRender:function (t,r,index) {
          //     let status = ''
          //     if (r.status == 0) {
          //       status = '草稿'
          //     } else if (r.status == 1) {
          //       status = '已提交'
          //     } else {
          //       status = '结束'
          //     }
          //     return status;
          //   }
          // },
          {
            title: '开始时间',
            align:"center",
            width:180,
            dataIndex: 'startTime',
            customRender: (text, row, index) => {
              if (text != ''){
                return moment(text).format("YYYY-MM-DD HH:mm");
              }
            },
            sorter: true
          },
          {
            title: '结束时间',
            align:"center",
            width:180,
            dataIndex: 'endTime',
            customRender: (text, row, index) => {
              if (text != ''){
                return moment(text).format("YYYY-MM-DD HH:mm");
              }
            },
            sorter: true
          },
          {
            title: '当前任务名称',
            align:"center",
            width:180,
            dataIndex: 'currentTaskName'
           },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            width:180,
            scopedSlots: { customRender: 'action' },
            fixed: "right"
          }
        ],
		url: {
          list: "/act/taskinst/done",
          delete: "/act/model/delete",
          deleteBatch: "/act/model/deleteBatch",
          exportXlsUrl: "model/model/exportXls",
          importExcelUrl: "model/model/importExcel",
      //校验绩效功能是否开放接口
      check:'/reimb/expenditureReimbInfo/check',
      getReimbIdByVirtualId:'/reimb/expenditureSubsistVirtual/getReimbIdByVirtualId',
       },
        addModel:true,
        modelSrc:'',
        pageUrl:'',
        pId:'',
        businessKey:"",
        taskId:"",
        tableId:"",
        title:"",
        // flow:Number,
        editUrl:"",
        innerpage:"",
        internalUrl:"",
        currentUsername:""
    }
  },
  computed: {
    importExcelUrl: function(){
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    }
  },

    created(){
      let user = Vue.ls.get('Login_Userinfo')
      this.currentUsername = user.realname
    },

    methods: {
      /**
       * @author pqz
       * @description 校验绩效功能是否开放
       */
      check(){
        return getAction(this.url.check, {}).then((res) => {
          return '1' == res.message
        })
      },
      customRender(record){
        let summary = record.summary;
        var m = summary.match( new RegExp('title":"'+'(.*?)'+'"') );
        return m ? m[ 1 ] : '';
      },
      Ellipsis(record){
        if(record==undefined || record==null || record==''){
          record=" "
        }
        if(record.length > 17){
          return record.substring(0,17)+"..."

        }else {
          return record
        }

      },
      // editModel(row){
      //   /*this.modelSrc=window._CONFIG['domianURL']+'/modeler.html?modelId='+row.id;
      //   this.addModel=true;*/
      //   let url =window._CONFIG['domianURL']+'/modeler.html?modelId='+row.id;
      //   window.open(url);
      // },
      // deployModel(row){
      //   const that = this;
      //
      //   this.$confirm({
      //     title: "提示",
      //     content: "请确认点击了左上角的保存按钮?",
      //     onOk: function () {
      //       that.loading = true;
      //       getAction("/act/model/deploy/",{id:row.id}).then((res)=>{
      //         if(res.success){
      //           that.$message.success(res.message);
      //         }else{
      //           that.$message.warning(res.message)
      //         }
      //       });
      //     }
      //   });
      //
      //
      // },
      showHistory(row){
        this.$refs.modalList.init(row.businessKey);
        this.$refs.modalList.title = "审批历史";
        this.$refs.modalList.disableSubmit = false;
      },
      async showDetail(record){
        this.$refs.taskDealModal.isOpenPlanPer = false
        this.$refs.taskDealModal.isOpenReimbPer = false
        //校验是否配置了绩效开关
        let isCheckPer =await this.check().then((res)=>{
          return res
        })
        this.businessKey = record.businessKey;
        if(this.businessKey.indexOf("expenditure_subsist_virtual.expenditure_subsist_virtual")!==-1){
          //预付款子流程，需要根据tableId获取报销主数据id
          await getAction(this.url.getReimbIdByVirtualId,{virtualId:record.tableId}).then(res=>{
            if(res.success){
              record.tableId=res.message
            }
          })
        }
        this.taskId = record.id;
        // this.title = record.title;
        // this.flow  = record.flow;
        this.editUrl = record.editUrl;
        this.internalUrl = record.internalUrl;

        // if(record.flow == 1){
        //   //flow为1的时候处理页面一直调用详情页面
        //   this.pageUrl = record.url;
        // }else{
        //   //flow不为1的时候处理页面调用FormKey填写的页面
        //   this.pageUrl = record.editUrl;
        // }

        if(record.editUrl!=null&&record.editUrl!=''&&record.editUrl!=undefined
            &&record.editUrl.indexOf("innerpage")!=-1){
            //FormKey存在而且包含内嵌页的时候处理页面显示详情页+显示详情页中的内嵌页
            this.innerpage = record.editUrl.split(':')[1];
            this.pageUrl = record.url;
        }else{
          //FormKey存在而且包含内嵌页的时候处理页面显示详情页+显示详情页中的内嵌页
          this.innerpage = record.url.split(':')[1];
          this.pageUrl = record.url;
        }


        // if(record.editUrl==null||record.editUrl==''||record.editUrl==undefined){
        //   //FormKey不存在的时候处理页面显示详情页面
        //   this.pageUrl = record.url;
        //   this.innerpage =null //为空 清空上次的值
        // }else if(record.editUrl.indexOf("innerpage")!=-1){
        //   //FormKey存在而且包含内嵌页的时候处理页面显示详情页+显示详情页中的内嵌页
        //   this.innerpage = record.editUrl.split(':')[1];
        //   this.pageUrl = record.url;
        // }else{
        //   //FormKey存在而且不包含内嵌页的时候处理页面调用FormKey填写的页面
        //   this.pageUrl = record.editUrl;
        // }
        this.$refs.taskDealModal.width = '90%';
        if(record.businessKey){
          if(record.businessKey.split('.')[0] == 'expenditure_plan'){
            // this.$refs.taskDealModal.onlyViewPrint = true;
            record.title=record.title.replace('详细','·事前申请')
            //校验是否配置了绩效开关
            this.$refs.taskDealModal.isOpenPlanPer = isCheckPer
          }else if(record.businessKey.split('.')[0] == 'expenditure_reimb_info'){
            // this.$refs.taskDealModal.onlyViewPrint = true;
            record.title=record.title.replace('详细','·事后报销')
            //校验是否配置了绩效开关
            this.$refs.taskDealModal.isOpenReimbPer = isCheckPer
          }else{
            // this.$refs.taskDealModal.onlyViewPrint = false;
          }
        }
        this.$refs.taskDealModal.onlyView = true;
        this.$refs.taskDealModal.expendType = record.expendType;
        this.$refs.taskDealModal.meetSignatureFlag = false
        this.$refs.taskDealModal.initData(record.tableId,(record.startUserId?(record.startUserId +'·'):'')+ record.title,record,"done");
        this.$refs.taskDealModal.disableSubmit = false;
        this.$refs.taskDealModal.childrenProcessDisabled = true;//childProcess只读
      },
      // toDetail(record){
      //   this.$router.push(record.url);
      // },
      cleanProcessData(row){
        const that = this;
        that.loading = true;
        //alert(row.businessKey);
        postAction("/handle/cleanProcessData/"+row.businessKey,{}).then((res)=>{
          if(res.success){

            that.$message.success(res.message);
            this.loadData(1);
          }else{
            that.$message.warning(res.message)
          }
        }).finally(() => {
          that.loading = false;
        });
      },

      backToThisTask(row){
        const that = this;
        that.loading = true;
        getAction("/handle/backToLastTask",{taskId:row.nextTaskId,lastTaskId:row.id}).then((res)=>{
          if(res.success){

            that.$message.success(res.message);
            this.loadData(1);
          }else{
            that.$message.warning(res.message)
          }
        }).finally(() => {
          that.loading = false;
        });
      }

    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less'
</style>